import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export type Label = { id: string, parent_id?: string|null, name: string, color?: string|null, description?: string|null, sort?: number }

export const useLabelsStore = defineStore('labels', () => {
  const items = ref<Label[]>([])
  const current = ref<Label | null>(null)
  const byId = computed<Record<string, Label>>(()=> Object.fromEntries(items.value.map(i=>[i.id, i])))
  const byIdPlain = computed(()=> ({ ...byId.value }))

  function setItems(list: Label[]){ items.value = list }
  function setCurrent(l: Label){ current.value = l }
  function addItem(label: Label){ items.value.push(label) }
  function updateItem(label: Label){ 
    const index = items.value.findIndex(i => i.id === label.id)
    if(index >= 0) {
      items.value[index] = label
    }
  }
  function removeItem(id: string){ 
    const index = items.value.findIndex(i => i.id === id)
    if(index >= 0) {
      items.value.splice(index, 1)
    }
  }

  // 统一的排序函数：按 sort 升序，其次按 name，最后按 id 以保证稳定
  function sortNodes(nodes: any[]): any[] {
    nodes.sort((a,b)=> {
      const sa = a.sort ?? 0
      const sb = b.sort ?? 0
      if(sa !== sb) return sa - sb
      const na = (a.name || '').localeCompare?.(b.name || '')
      if(na !== 0) return na
      return (a.id || '').localeCompare(b.id || '')
    })
    for(const n of nodes){
      if(n.children && n.children.length){
        sortNodes(n.children)
      }
    }
    return nodes
  }

  function toTree(list: Label[]): any[] {
    const map: Record<string, any> = {}
    const roots: any[] = []
    list.forEach(l => map[l.id] = { ...l, children: [] })
    list.forEach(l => {
      const node = map[l.id]
      if(l.parent_id){
        map[l.parent_id]?.children.push(node)
      }else{
        roots.push(node)
      }
    })
    return sortNodes(roots)
  }

  function filteredTree(q: string){
    if(!q) return toTree(items.value)
    const lower = q.toLowerCase()

    // 构建完整树（不立即排序，稍后统一）
    const map: Record<string, any> = {}
    items.value.forEach(l => map[l.id] = { ...l, children: [] })
    items.value.forEach(l => {
      const node = map[l.id]
      if(l.parent_id && map[l.parent_id]){
        map[l.parent_id].children.push(node)
      }
    })
    // 先对每个节点的 children 排序
    Object.values(map).forEach(n => { if(n.children) sortNodes(n.children) })

    // 找到所有匹配节点（名字包含关键词）
    const matched = new Set<string>(items.value.filter(i => (i.name||'').toLowerCase().includes(lower)).map(i => i.id))
    if(matched.size === 0) return []

    // 克隆节点：当遇到匹配节点的子孙时，为避免 node-key 冲突，不再把该子孙包含在当前分支中
    const cloneWithoutMatchedDesc = (node: any): any => {
      const cloned = { ...node, children: [] as any[] }
      for(const child of node.children || []){
        if(matched.has(child.id)) continue // 子孙已另作根节点展示，避免重复
        cloned.children.push(cloneWithoutMatchedDesc(child))
      }
      // 克隆完成后对其子元素再排序一次
      if(cloned.children.length) sortNodes(cloned.children)
      return cloned
    }

    // 将匹配到的节点作为根节点展示
    const result: any[] = []
    for(const id of matched){
      const node = map[id]
      if(node){
        result.push(cloneWithoutMatchedDesc(node))
      }
    }
  return sortNodes(result)
  }

  return { items, current, byId, byIdPlain, setItems, setCurrent, addItem, updateItem, removeItem, filteredTree }
})
